const md5 = require('blueimp-md5')
const moment = require('moment')
const db = require('./db.js')

function getSql (key, val) {
	return `select * from users where ${key}='${val}'`
}

exports.getUserByCondition = async function(key, val) {
	const strSql = getSql(key, val)
	const [user] = await db.query(strSql)
	return user
}

exports.createdUser = async function (body) {
	const strSql = `
		INSERT INTO users(username,password,email,nickname,create_time,modify_time) values(
			'${body.email}',
			'${md5(md5(body.password))}',
			'${body.email}',
			'${body.nickname}',
			'${moment().format()}',
			'${moment().format('YYYY-MM-DD hh:mm:ss')}'
		)
	`
	// 把容易出错的代码放到 try-catch 代码块中
	// try 中的代码一旦出错，会立即进入 catch 代码块
	try {
		const ret = await db.query(strSql)
		return ret.insertId
	} catch(err) {
		throw err
	}
}